<template>
  <div class="page-container" v-global-loading="loading">
    <div class="page-card-container">
      <div style="display: flex; justify-content: end; margin-bottom: 10px">
        <div class="commonBtn-primary" @click="operation(1, 1, 1)">新增</div>
      </div>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        :defaultExpandAllRows="true"
      >
        <template #bodyCell="{text, record, index, column}">
          <template v-if="column.title == '操作'">
            <span
              class="pointer c-primaryColor"
              @click="operation(2, record.id, index)"
              v-if="!record.isUpdata"
              >编辑</span
            >
            <span
              class="pointer c-primaryColor"
              @click="operation(3, record.id, index)"
              v-if="record.isUpdata"
              >保存&nbsp;&nbsp;</span
            >
            <span
              class="pointer c-primaryColor"
              @click="operation(4, record.id, index)"
              v-if="record.isUpdata"
              >取消</span
            >
          </template>
          <template v-if="column.title == '模板名称'">
            <div
              style="
                height: 30px;
                line-height: 30px;
                padding-left: 12px;
                text-align: left;
              "
              v-show="!record.isUpdata"
            >
              {{ tableData[index].name }}
            </div>
            <a-input
              v-model:value="tableData[index].name"
              v-show="record.isUpdata"
            ></a-input>
          </template>
        </template>
        <template #expandedRowRender="e">
          <div style="padding: 10px">
            <div
              style="display: flex; justify-content: end; margin-bottom: 10px"
            >
              <div
                class="commonBtn-primary mr-20"
                @click="assignOperation(1, 1, 1, e)"
              >
                单次添加指定包邮区域
              </div>
              <div
                class="commonBtn-primary mr-20"
                @click="assignOperation(2, 1, 1, e)"
              >
                批量添加指定包邮区域
              </div>
              <div
                class="commonBtn-primary mr-20"
                @click="assignOperation(3, 1, 1, e)"
              >
                批量修改包邮金额
              </div>
              <div>
                <span>包邮金额:</span>&nbsp;&nbsp;
                <a-input-number
                  v-model:value="e.record.fee"
                  min="0"
                ></a-input-number>
              </div>
            </div>
            <a-table
              size="small"
              :loading="tableLoading1"
              :dataSource="e.record.mailAreas"
              :columns="columns1"
              bordered
              :pagination="false"
              class="table_box"
              :scroll="{y: 500}"
              :row-selection="{
                onChange: (selectedRowKeys) => {
                  e.record.returnedDataID = selectedRowKeys;
                },
                getCheckboxProps: (record) => ({
                  disabled: !record.id
                }),
                selectedRowKeys: e.record.returnedDataID
              }"
              row-key="id"
            >
              <template #bodyCell="{record, index, text, column}">
                <template v-if="column.title == '操作'">
                  <div style="display: flex; justify-content: center">
                    <div
                      class="commonBtn-primary mr-20"
                      @click="assignOperation(4, record.id, index, e)"
                      v-if="!record.isUpdata"
                    >
                      编辑
                    </div>
                    <div
                      class="commonBtn-primary mr-20"
                      @click="assignOperation(5, record.id, index, e)"
                      v-if="!record.isUpdata"
                    >
                      删除
                    </div>
                    <div
                      class="commonBtn-warning mr-20"
                      @click="assignOperation(6, record.id, index, e)"
                      v-if="record.isUpdata"
                    >
                      保存
                    </div>
                    <div
                      class="commonBtn-primary mr-20"
                      @click="assignOperation(7, record.id, index, e)"
                      v-if="record.isUpdata"
                    >
                      取消
                    </div>
                  </div>
                </template>
                <template v-if="column.title == '序号'">
                  {{ index + 1 }}
                </template>
                <template v-if="column.title == '省'">
                  <div v-if="record.id">
                    {{ record.province }}
                  </div>
                  <a-select
                    v-else
                    v-model:value="e.record.mailAreas[index].provinceId"
                    :filter-option="filterOption"
                    show-search
                    allowClear
                    style="width: 100%"
                    placeholder="请选择省份"
                    @change="
                      (a) => {
                        changeCity(a, 'province', e, index);
                      }
                    "
                  >
                    <a-select-option
                      :value="item.code"
                      v-for="(item, i) in e.record.mailAreas[index].district"
                      :key="i"
                      :title="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.title == '市'">
                  <div v-if="record.id">
                    {{ record.city }}
                  </div>
                  <a-select
                    v-else
                    v-model:value="e.record.mailAreas[index].cityId"
                    :filter-option="filterOption"
                    show-search
                    allowClear
                    style="width: 100%"
                    placeholder="请选择城市"
                    @change="
                      (a) => {
                        changeCity(a, 'city', e, index);
                      }
                    "
                  >
                    <a-select-option
                      :value="item.code"
                      v-for="(item, i) in e.record.mailAreas[index]
                        .provinceList"
                      :key="i"
                      :title="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.title == '县'">
                  <div v-if="record.id">
                    {{ record.county }}
                  </div>
                  <a-select
                    v-else
                    v-model:value="e.record.mailAreas[index].countyId"
                    :filter-option="filterOption"
                    show-search
                    allowClear
                    style="width: 100%"
                    placeholder="请选择区县"
                    @change="
                      (a) => {
                        changeCity(a, 'district', e, index);
                      }
                    "
                  >
                    <a-select-option
                      :value="item.code"
                      v-for="(item, i) in e.record.mailAreas[index].cityList"
                      :key="i"
                      :title="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.title == '包邮金额(元)'">
                  <div v-if="record.id && !record.isUpdata">
                    {{ e.record.mailAreas[index].fee }}元
                  </div>
                  <a-input-number
                    v-else
                    v-model:value="e.record.mailAreas[index].fee"
                    style="width: 100%"
                    min="0"
                  ></a-input-number>
                </template>
              </template>
            </a-table>
          </div>
        </template>
      </a-table>
      <a-modal
        v-model:open="visible"
        width="800px"
        title="请输入包邮金额"
        :footer="null"
        :maskClosable="false"
      >
        <div v-global-loading="modalloading">
          <div style="display: flex; justify-content: end; margin-bottom: 10px">
            <div class="commonBtn-primary mr-20" @click="assign">
              {{ isOpen ? "批量修改包邮金额" : "开启批量修改包邮金额" }}
            </div>
            <div style="margin-right: 30px; margin-left: 10px">
              <span>包邮金额:</span>&nbsp;&nbsp;
              <a-input-number
                v-model:value="fee"
                :disabled="!isOpen"
              ></a-input-number>
            </div>
          </div>
          <a-table
            size="small"
            :loading="tableLoading1"
            :dataSource="formData"
            :columns="columns2"
            bordered
            :pagination="false"
            class="table_box"
            :scroll="{y: 500}"
            :row-selection="{
              onChange: (selectedRowKeys) => {
                returnedIndex = selectedRowKeys;
              },
              getCheckboxProps: (record) => ({
                disabled: !isOpen
              }),
              selectedRowKeys: returnedIndex
            }"
            row-key="id"
          >
            <template #bodyCell="{record, index, text, column}">
              <template v-if="column.title == '序号'">
                {{ index + 1 }}
              </template>
              <template v-if="column.title == '省'">
                {{ record.province }}
              </template>
              <template v-if="column.title == '市'">
                {{ record.city }}
              </template>
              <template v-if="column.title == '县'">
                {{ record.county }}
              </template>
              <template v-if="column.title == '包邮金额(元)'">
                <a-input-number
                  v-model:value="record.fee"
                  style="width: 100%"
                ></a-input-number>
              </template>
            </template>
          </a-table>
          <div style="display: flex; justify-content: end; margin-top: 10px">
            <a-button style="margin-right: 14px" @click="submit(false)"
              >取消</a-button
            >
            <a-button type="primary" @click="submit(true)">确定</a-button>
          </div>
        </div>
      </a-modal>
      <DesignatedArea
        @ok="designatedOk"
        ref="DesignatedAreaRef"
      ></DesignatedArea>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, h, inject, onActivated, onMounted, nextTick} from "vue";
import district from "@/utils/city";
import DesignatedArea from "@/components/functional/DesignatedArea.vue";
import {
  postageManageList,
  postageManageCreate,
  postageManageUpdate,
  postageManageCreateMailArea,
  postageManageUpdateMailArea,
  postageManageMailAreaDelete
} from "@/api/merchandise/postage";
import {message} from "ant-design-vue";
const filterOption = (input: string, option: any) => {
  return option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const isUpdata = ref(false);
const modalloading = ref(false);
const templateId = ref();
//已经选中的集合
const returnedIndex = ref([]);
//是否开启批量
const isOpen = ref(false);
//包邮金额
const fee = ref(0);
const assign = () => {
  if (isOpen.value) {
    //已开启提交包邮金额
    formData.value.forEach((item, index) => {
      returnedIndex.value.forEach((v) => {
        if (item.id == v) {
          item.fee = fee.value;
        }
      });
    });
    message.success("操作成功!");
    isOpen.value = false;
    fee.value = 0;
    returnedIndex.value = [];
  } else {
    //开启批量操作
    isOpen.value = true;
    message.success("已开启批量操作，请选择需要修改的项以及输入包邮金额！");
  }
};
const formData = ref();
//选择完日期回调
const designatedOk = (data) => {
  let list: any = [];
  data.forEach((item) => {
    let obj: any = {};
    let index = 0;
    obj = {
      postageManageId: templateId.value,
      provinceId: item.code,
      province: item.name,
      fee: 0,
      id: index
    };
    if (item.children.length != item.childrenNum || ischeckAll(item.children)) {
      item.children.forEach((child) => {
        let obj1 = {
          postageManageId: templateId.value,
          provinceId: item.code,
          province: item.name,
          cityId: child.code,
          city: child.name,
          fee: 0,
          id: index
        };
        if (child.children.length != child.childrenNum) {
          child.children.forEach((v) => {
            let obj2 = {
              postageManageId: templateId.value,
              provinceId: item.code,
              province: item.name,
              cityId: child.code,
              city: child.name,
              countyId: v.code,
              county: v.name,
              fee: 0,
              id: index
            };
            list.push(obj2);
            index++;
          });
        } else {
          list.push(obj1);
          index++;
        }
      });
    } else {
      list.push(obj);
      index++;
    }
  });
  formData.value = list;
  visible.value = true;
};
//批量创建指定区域
const submit = (type) => {
  if (type) {
    modalloading.value = true;
    postageManageCreateMailArea(formData.value)
      .then((res) => {
        message.success("创建成功!");
        loadPagination();
        visible.value = false;
      })
      .finally(() => {
        modalloading.value = false;
      });
  } else {
    visible.value = false;
  }
};
const DesignatedAreaRef = ref();
const calcCanUseHeight: any = inject("calcCanUseHeight");
onActivated(() => {
  calcCanUseHeight();
});
onMounted(() => {
  calcCanUseHeight();
});
const tableLoading = ref<boolean>(false);
const tableLoading1 = ref<boolean>(false);
const loading = ref<boolean>(false);
const form: any = ref({});
const visible = ref(false);
//模板操作
const operation = (type: number, id: number | string, index: number) => {
  if (type == 1) {
    //创建
    if (tableData.value.length == 1) {
      message.error("已有一条模板!");
    } else {
      if (isUpdata.value) {
        message.warning("请完成上一步编辑或新增的操作");
      } else {
        tableData.value.push({name: "", isUpdata: true});
        isUpdata.value = true;
      }
    }
  } else if (type == 2) {
    //编辑
    if (isUpdata.value) {
      message.warning("请完成上一步编辑或新增的操作");
    } else {
      isUpdata.value = true;
      tableData.value[index].isUpdata = true;
      tableData.value[index].copyName = tableData.value[index].name;
    }
  } else if (type == 3) {
    //保存
    if (id) {
      //编辑
      loading.value = true;
      postageManageUpdate(tableData.value[index])
        .then(() => {
          loadPagination();
          isUpdata.value = false;
          message.success("编辑成功");
          tableData.value[index].isUpdata = false;
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      //创建
      loading.value = true;
      postageManageCreate(tableData.value[index])
        .then(() => {
          loadPagination();
          isUpdata.value = false;
          message.success("创建成功");
          tableData.value[index].isUpdata = false;
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } else if (type == 4) {
    //取消
    if (id) {
      isUpdata.value = false;
      tableData.value[index].name = tableData.value[index].copyName;
      tableData.value[index].isUpdata = false;
    } else {
      isUpdata.value = false;
      tableData.value.splice(index, 1);
      tableData.value[index].isUpdata = false;
    }
  }
};
const box = ref();
//指定包邮操作
const assignOperation = (
  type: number,
  id: number | string,
  index: number,
  e: any
) => {
  if (type == 1) {
    //单次添加
    if (isUpdata.value) {
      message.warning("请完成上一步编辑或新增的操作");
    } else {
      if (!tableData.value[e.index].mailAreas) {
        tableData.value[e.index].mailAreas = [];
      }
      isUpdata.value = true;
      tableData.value[e.index].mailAreas.push({
        postageManageId: e.record.id,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        countyId: null,
        county: null,
        fee: 0,
        district: district,
        cityList: [],
        provinceList: [],
        isUpdata: true
      });
      let table_body = document.querySelectorAll(".table_box");
      box.value =
        table_body[table_body.length - 1].querySelector(".ant-table-body");
      nextTick(() => {
        let boxScrollTop = box.value.scrollHeight - box.value.clientHeight;
        box.value.scrollTop = boxScrollTop;
      });
    }
  } else if (type == 2) {
    //批量添加
    if (isUpdata.value) {
      message.warning("请完成上一步编辑或新增的操作");
    } else {
      DesignatedAreaRef.value.visible1 = true;
      templateId.value = e.record.id;
    }
  } else if (type == 3) {
    //批量修改包邮金额
    if (e.record.returnedDataID && e.record.returnedDataID.length) {
      if (e.record.fee) {
        let ids = e.record.returnedDataID.join(",");
        loading.value = true;
        postageManageUpdateMailArea({ids, fee: e.record.fee})
          .then(() => {
            message.success("修改成功!");
            loadPagination();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        message.error("请输入包邮金额");
      }
    } else {
      message.error("请选择指定区域");
    }
  } else if (type == 4) {
    //编辑
    if (isUpdata.value) {
      message.warning("请完成上一步编辑或新增的操作");
    } else {
      isUpdata.value = true;
      tableData.value[e.index].mailAreas[index].copyData = JSON.parse(
        JSON.stringify(tableData.value[e.index].mailAreas[index])
      );
      tableData.value[e.index].mailAreas[index].isUpdata = true;
    }
  } else if (type == 5) {
    //删除
    if (isUpdata.value) {
      message.warning("请完成上一步编辑或新增的操作");
    } else {
      loading.value = true;
      postageManageMailAreaDelete({id})
        .then(() => {
          message.success("删除成功!");
          loadPagination();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } else if (type == 6) {
    //保存
    if (tableData.value[e.index].mailAreas[index].id) {
      //编辑
      loading.value = true;
      postageManageUpdateMailArea({
        ids: id,
        fee: tableData.value[e.index].mailAreas[index].fee
      })
        .then((res) => {
          message.success("编辑成功");
          loadPagination();
          isUpdata.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      let provinceList = JSON.parse(
        JSON.stringify(tableData.value[e.index].mailAreas[index].provinceList)
      );
      let district = JSON.parse(
        JSON.stringify(tableData.value[e.index].mailAreas[index].district)
      );
      let cityList = JSON.parse(
        JSON.stringify(tableData.value[e.index].mailAreas[index].cityList)
      );
      delete tableData.value[e.index].mailAreas[index].provinceList;
      delete tableData.value[e.index].mailAreas[index].district;
      delete tableData.value[e.index].mailAreas[index].cityList;
      //创建
      if (tableData.value[e.index].mailAreas[index].provinceId) {
        loading.value = true;
        postageManageCreateMailArea([tableData.value[e.index].mailAreas[index]])
          .then((res) => {
            message.success("创建成功");
            loading.value = false;
            loadPagination();
            isUpdata.value = false;
          })
          .catch(() => {
            loading.value = false;
            tableData.value[e.index].mailAreas[index].provinceList =
              provinceList;
            tableData.value[e.index].mailAreas[index].district = district;
            tableData.value[e.index].mailAreas[index].cityList = cityList;
          });
      } else {
        message.error("请选择地区");
      }
    }
  } else if (type == 7) {
    //取消
    isUpdata.value = false;
    if (tableData.value[e.index].mailAreas[index].id) {
      tableData.value[e.index].mailAreas[index] =
        tableData.value[e.index].mailAreas[index].copyData;
    } else {
      tableData.value[e.index].mailAreas.splice(index, 1);
    }
  }
};
const tableData = ref<Array<any>>([{}]);
const columns = ref<Array<object>>([
  {
    title: "模板名称",
    dataIndex: "name",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "caozuo",
    align: "center",
    width: 150
  }
]);
const columns1 = ref<Array<object>>([
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    width: 60
  },
  {
    title: "省",
    dataIndex: "provinceId",
    align: "center",
    width: 150
  },
  {
    title: "市",
    dataIndex: "cityId",
    align: "center",
    width: 150
  },
  {
    title: "县",
    dataIndex: "countyId",
    align: "center",
    width: 150
  },
  {
    title: "包邮金额(元)",
    dataIndex: "fee",
    align: "center",
    width: 150
  },
  {
    title: "操作",
    dataIndex: "caozuo",
    align: "center",
    width: 200,
    fixed: "right"
  }
]);
const columns2 = ref<Array<object>>([
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    width: 60
  },
  {
    title: "省",
    dataIndex: "provinceId",
    align: "center",
    width: 150
  },
  {
    title: "市",
    dataIndex: "cityId",
    align: "center",
    width: 150
  },
  {
    title: "县",
    dataIndex: "countyId",
    align: "center",
    width: 150
  },
  {
    title: "包邮金额(元)",
    dataIndex: "fee",
    align: "center",
    width: 150
  }
]);
//省市区三级联动
const changeCity = (a, b, e, index) => {
  if (b == "province") {
    e.record.mailAreas[index].cityId = null;
    e.record.mailAreas[index].city = null;
    e.record.mailAreas[index].countyId = null;
    e.record.mailAreas[index].county = null;
    e.record.mailAreas[index].provinceList = [];
    e.record.mailAreas[index].cityList = [];
    if (a) {
      district.forEach((item) => {
        if (item.code == a) {
          e.record.mailAreas[index].provinceList = item.children;
          e.record.mailAreas[index].provinceId = item.code;
          e.record.mailAreas[index].province = item.name;
        }
      });
    } else {
      e.record.mailAreas[index].provinceId = null;
      e.record.mailAreas[index].province = null;
    }
  } else if (b == "city") {
    e.record.mailAreas[index].cityList = [];
    e.record.mailAreas[index].countyId = null;
    e.record.mailAreas[index].county = null;
    if (a) {
      e.record.mailAreas[index].provinceList.forEach((item) => {
        if (item.code == a) {
          e.record.mailAreas[index].cityList = item.children;
          e.record.mailAreas[index].cityId = item.code;
          e.record.mailAreas[index].city = item.name;
        }
      });
    } else {
      e.record.mailAreas[index].cityId = null;
      e.record.mailAreas[index].city = null;
    }
  } else if (b == "district") {
    if (a) {
      e.record.mailAreas[index].cityList.forEach((item) => {
        if (item.code == a) {
          e.record.mailAreas[index].countyId = item.code;
          e.record.mailAreas[index].county = item.name;
        }
      });
    } else {
      e.record.mailAreas[index].countyId = null;
      e.record.mailAreas[index].county = null;
    }
  }
};
//获取数据
const loadPagination = (): void => {
  tableLoading.value = true;
  postageManageList()
    .then((res) => {
      tableData.value = res.data;
      if (tableData.value) {
        compile(tableData.value);
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
const compile = (list) => {
  list.forEach((v) => {
    v.returnedDataID = [];
    if (v.mailAreas) {
      v.mailAreas.forEach((item, index) => {
        item.district = district;
        district.forEach((a) => {
          if (a.code == item.provinceId) {
            item.provinceList = a.children;
          }
        });
        if (item.provinceList) {
          item.provinceList.forEach((a) => {
            if (a.code == item.cityId) {
              item.cityList = a.children;
            }
          });
        }
      });
    }
  });
};
const ischeckAll = (list) => {
  let flag = false;
  list.forEach((item) => {
    if (item.children.length != item.childrenNum) {
      flag = true;
    }
  });
  return flag;
};
loadPagination();
</script>

<style lang="less" scoped></style>
